//
//  TuiJianViewController.m
//  NewPro
//
//  Created by RYX on 2019/7/23.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "TuiJianViewController.h"
#import "IncomeTwoViewController.h"
#import "PutForwardRecordViewController.h"
#import "PutForwardRecordStore.h"
#import "BandViewController.h"
#import "IncomeModel.h"
#import "BandCardStore.h"
#import "BankCarList.h"
#import "BandCardModel.h"
#import "PosApplyViewController.h"
#import "NewWalletList.h"
#import "NewWalletModel.h"
#import "InputTradingPassWordView.h"
#import "SetTradingPassWordViewController.h"
#import "TXModel.h"
#import "TuiJianCell.h"
#import "NewWalletStore.h"

@interface TuiJianViewController ()<UITableViewDelegate,UITableViewDataSource,TuiJianCellDelegate>{
    
    BOOL haveBgView;
}

@property (nonatomic,strong) IncomeModel *paramterModel;
@property (nonatomic,strong) InputTradingPassWordView *tradingPassWordView;
@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) UITableView *tableView;

@end

@implementation TuiJianViewController

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        [self.view addSubview:_tableView];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self getTXInfo];
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        self.tableView.mj_header = header;
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.equalTo(self.view);
            
        }];
    }
    
    return _tableView;
}

- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        [_bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didBgViewClick)]];
    }
    return _bgView;
}

- (void)didBgViewClick{
    
    [self.view endEditing:YES];
}

- (InputTradingPassWordView *)tradingPassWordView{
    
    if (!_tradingPassWordView) {
        
        CGFloat speace = 29;
        CGFloat scale = 0.67;
        CGFloat width = (ScreenWidth - speace * 2);
        CGFloat height = width * scale;
        
        _tradingPassWordView = [[InputTradingPassWordView alloc] initWithFrame:CGRectMake(speace, ScreenHeight, width, height)];
        _tradingPassWordView.wherefrom = @"FanXianViewController";
        
        MJWeakSelf
        //关闭按钮点击回调
        [_tradingPassWordView returnCloseBlock:^{
            [UIView animateWithDuration:0.25 animations:^{
                
                self->haveBgView = NO;
                weakSelf.tradingPassWordView.y = ScreenHeight;
                weakSelf.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
            } completion:^(BOOL finished) {
                [weakSelf.bgView removeFromSuperview];
            }];
        }];
        
        //确定按钮点击回调
        [_tradingPassWordView returnSureBlock:^(NSString *code, UIButton *sender) {
            
            [weakSelf putFoward:code andBtn:sender];
        }];
        
    }
    return _tradingPassWordView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.paramterModel = [[IncomeModel alloc] init];
    self.paramterModel.secret = @"";
    
    [self setUI];
    
    [self getBankInfo];
    [self getTXInfo];
    
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)setUI{
    
    [self setNavBarWithTitle:@"推荐奖励"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"img_more"] style:UIBarButtonItemStylePlain target:self action:@selector(onMore)];
    
    [self.tableView reloadData];
    
    [self.view insertSubview:self.tradingPassWordView belowSubview:self.navigationController.navigationBar];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TuiJianCell *cell = [TuiJianCell tempWithTableView:tableView];
    cell.backgroundColor = BASECOLOR;
    cell.delegate = self;
    cell.bankNoLa.text = [NSString stringWithFormat:@"%@（%@）",[NewWalletList sharedInstance].fx_bank,[[NewWalletList sharedInstance].fx_bankno substringFromIndex:[NewWalletList sharedInstance].fx_bankno.length - 4]];
    cell.dqyeLa.text = [NSString stringWithFormat:@"当前余额¥%.2f,",[NewWalletList sharedInstance].selectModel.recommendAmount];
    cell.ktxla.text = [NSString stringWithFormat:@"可提现金额¥%.2f",[NewWalletList sharedInstance].selectModel.recommendAmount];
    cell.beizhuLa.text = [NewWalletList sharedInstance].txModel.tip_recommend_amount;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - 更多
- (void)onMore{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"提现记录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        PutForwardRecordViewController *VC = [[PutForwardRecordViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }]];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

#pragma mark - 获取默认银行卡
- (void)getBankInfo{
    
    MJWeakSelf
    BandCardStore *store = [[BandCardStore alloc] init];
    [store getBandCardListSuccess:^(NSArray *listArr) {
        
        for (BandCardModel *model in listArr) {
            
            if ([model.defaultCard intValue] == 1) {
                
                [NewWalletList sharedInstance].fx_bank = model.bank;
                [NewWalletList sharedInstance].fx_bankno = model.bankNo;
                
                weakSelf.paramterModel.bank = model.bank;
                weakSelf.paramterModel.bankNo = model.bankNo;
                weakSelf.paramterModel.cardId = model.uid;
                
                [weakSelf.tableView reloadData];
            }
        }
        
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

#pragma mark - 获取提现信息
- (void)getTXInfo{
    
    MJWeakSelf
    NewWalletStore *store = [[NewWalletStore alloc] init];
    [store getTXInfoSuccess:^(TXModel *model) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
        
    } Failure:^(NSError *error) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    if (haveBgView) {
        
        //获取键盘的高度
        NSDictionary *userInfo = [notification userInfo];
        NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [value CGRectValue];
        int height = keyboardRect.size.height;
        self.tradingPassWordView.y = ScreenHeight - height - self.tradingPassWordView.height - iPhoneX_Top - 10;
    }
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    if (haveBgView) {
        
        self.tradingPassWordView.centerY = self.view.centerY - iPhoneX_Top - TAB_BAR_HEIGHT;
    }
}

#pragma mark - FanXianCellDelegate
#pragma mark - 选择银行卡
- (void)onSelectBankBtn{
    
    BandViewController *VC = [[BandViewController alloc] init];
    VC.tixian = YES;
    
    MJWeakSelf
    VC.myblock = ^{
        
        BandCardModel *model = [BankCarList sharedInstance].selectBandModel;
        [NewWalletList sharedInstance].fx_bank = model.bank;
        [NewWalletList sharedInstance].fx_bankno = model.bankNo;
        
        weakSelf.paramterModel.bank = model.bank;
        weakSelf.paramterModel.bankNo = model.bankNo;
        weakSelf.paramterModel.cardId = model.uid;
        [weakSelf.tableView reloadData];
        
    };
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 点击提现按钮
- (void)onTiXianBtn{
    
    [self.view endEditing:YES];
    
    if (![NewWalletList sharedInstance].tradingPassWordSeted) {
        
        SetTradingPassWordViewController *VC = [[SetTradingPassWordViewController alloc] init];
        [self.navigationController pushViewController:VC animated:YES];
        
        return;
    }
    
    if ([NewWalletList sharedInstance].fx_money.length <= 0) {
        
        return [self showMBPError:@"输入提现金额"];
    }
    
    NSInteger money = [[NewWalletList sharedInstance].fx_money integerValue];
    
    if(money > [NewWalletList sharedInstance].selectModel.recommendAmount){
        
        return [self showMBPError:@"提现金额不能超过可提现金额!"];
    }
    
    [self.view insertSubview:self.bgView belowSubview:self.tradingPassWordView];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self->haveBgView = YES;
        self.tradingPassWordView.y = iPhoneX_Top;
        [self.tradingPassWordView setBecomeFirstResponder:YES];
        self.bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    }];
}

#pragma mark - 我要购机
- (void)onBuyBtn{
    
    PosApplyViewController *VC = [[PosApplyViewController alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - 提现请求
- (void)putFoward:(NSString *)secret andBtn:(UIButton *)sender{
    
    PutForwardRecordStore *store = [[PutForwardRecordStore alloc] init];
    MJWeakSelf
    [store putForwardWithSecret:secret amount:[NewWalletList sharedInstance].fx_money type:@"4" cardId:self.paramterModel.cardId Success:^{
        
        sender.enabled = YES;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:PUTFORWARDSUCCESS object:nil];
        
        IncomeTwoViewController *VC = [[IncomeTwoViewController alloc] init];
        VC.money = [NewWalletList sharedInstance].fx_money;
        VC.band = [NSString stringWithFormat:@"%@ 尾号%@",self.paramterModel.bank,[self->_paramterModel.bankNo substringFromIndex:self->_paramterModel.bankNo.length - 4]];
        [weakSelf.navigationController pushViewController:VC animated:YES];
        
    } Failure:^(NSError *error) {
        
        sender.enabled = YES;
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
}

@end
